import { MobilePageDesigner } from 'components/mobilePageDesigner';
import { StationService as UserStation } from 'user/services/stationService';
import { StationService as AdminStation, guid, StationService } from 'admin/services/station';
import { ShoppingService } from 'admin/services/shopping';
import { product as dataSource, freightSolution as dsFreightSolution } from 'admin/services/dataSource';
import { State as CarouselState } from 'components/carousel/control'
import { productTemplate as dsProductTemplate } from 'admin/services/dataSource';
import { Dropdown } from 'admin/controls/dropdown';
import ReactDOM = require('react-dom');
import React = require('react');
import * as chitu from "maishu-chitu";

export default async function (page: chitu.Page) {

    var defaultFreightSolutionId = '';
    let productId = (page.data.id || page.data.parentId) as string;
    let pageData: PageData;
    if (productId) {
        // pageData 的 id 和 商品 一样
        let userStation = page.createService(UserStation);
        pageData = await userStation.pages.pageDataById(productId);
        let product = productFromPageData(pageData);
        // parentId 不为空，是要复制一份商品，源 id 为 parentId
        if (page.data.parentId) {
            pageData.id = null;
            delete product.Id;
        }
        else {
            product.Id = productId;
        }
    }
    else {
        pageData = {
            name: '*product',
            controls: [
                { controlName: 'carousel', controlId: guid(), data: { autoplay: false }, position: 'view' },
                { controlName: 'productInfo', controlId: guid(), selected: true, position: 'view' },
                { controlName: 'html', controlId: guid(), data: { emptyText: '暂无商品简介，点击设置商品简介，还可以添加其他组件。' }, position: 'view' },
                { controlName: 'productInfoBottomBar', controlId: guid(), position: 'footer' }
            ]
        }
    }

    //===========================================================
    // 通过 itemWidth 设置列表项的宽
    let carousel = pageData.controls.filter(o => o.controlName == 'carousel')[0];
    console.assert(carousel != null);
    let carouselState = (carousel.data as CarouselState);
    carouselState.itemScale = 1;
    carouselState.clickType = 'showImage';
    //===========================================================

    ReactDOM.render(<ProductEditPage {...{ pageData, page, defaultFreightSolutionId }} />, page.element);
}

function productFromPageData(pageData: PageData) {
    let productInfo = pageData.controls.filter(o => o.controlName == 'productInfo')[0];
    console.assert(productInfo != null);

    let product: Product = (productInfo.data || {}).product || {};
    return product;
}

type Props = {
    pageData: PageData, page: chitu.Page,
    defaultFreightSolutionId: string
} & React.Props<ProductEditPage>;

type State = {
    selectedProductTemplate?: PageData,
    productTemplates: PageData[],
}

class ProductEditPage extends React.Component<Props, State> {

    ddnFreight: Dropdown<FreightSolution>;
    ddnTemplate: Dropdown<PageData>;
    freightElement: HTMLSelectElement;
    private templatesElement: HTMLSelectElement;
    constructor(props) {
        super(props);
        this.state = {
            productTemplates: [],
        };
    }

    designer: MobilePageDesigner;
    async saveProduct(pageData: PageData): Promise<any> {
        let { page } = this.props;
        let station = page.createService(AdminStation);

        let product: Product = productFromPageData(pageData);
        product.FreightSolutionId = this.freightElement.value;

        //============================================================
        // 要先更新 Product
        if (!product.Id) {
            await dataSource.insert(product);//, { parentId }
        }
        else {
            await dataSource.update(product);//, { parentId }
        }
        //============================================================
        // TODO 考虑 savePageData 失败的情况
        pageData.id = product.Id;
        await station.savePageData(pageData);

        console.assert(pageData.id != null);
    }

    async setProductTemplate(templateId: string) {
        this.props.pageData.templateId = templateId;
        this.setState(this.state);
    }

    async componentDidMount() {
        let pageData = this.props.pageData;
        this.ddnTemplate = new Dropdown({
            element: this.templatesElement,
            value: pageData.templateId || '',
            dataSource: dsProductTemplate,
            nameField: 'name',
            valueField: 'id'
        });

        let shopping = this.props.page.createService(ShoppingService);
        let product: Product = productFromPageData(pageData);
        console.assert(product != null);


        let { defaultFreightSolutionId } = this.props;
        let ds = Object.assign({}, dsFreightSolution, {
            executeSelect: async () => {
                var items = await shopping.freightSolutions();
                items = items.filter(o => !o.IsDefault);
                return items;
            }
        })
        this.ddnFreight = new Dropdown({
            element: this.freightElement,
            value: product.FreightSolutionId || defaultFreightSolutionId,
            dataSource: ds,
            nameField: 'Name',
            valueField: 'Id'
        })
    }

    render() {

        let { page, pageData } = this.props;

        return <MobilePageDesigner pageData={pageData}
            save={(pageData) => this.saveProduct(pageData)}
            elementPage={page}
            showComponentToolbar={true}
            rightButtons={[
                <button key={100} className="btn btn-sm btn-primary" onClick={() => history.back()}>
                    <i className="icon-reply" />
                    <span>返回</span>
                </button>
            ]}
            panel={
                <div className="well clearfix">
                    <label className="pull-left" style={{ width: 60, paddingTop: 6 }}>模板</label>
                    <select className="form-control pull-left" style={{ maxWidth: 200 }}
                        onChange={(e) => {
                            let productTemplateId = (e.target as HTMLSelectElement).value;
                            this.setProductTemplate(productTemplateId);
                        }}
                        ref={(e: HTMLSelectElement) => this.templatesElement = e || this.templatesElement} >
                        <option value="">请选择商品模板</option>
                    </select>
                    <label className="pull-left" style={{ width: 120, paddingTop: 6, paddingLeft: 20 }}>运费模板</label>
                    <select className="form-control" style={{ maxWidth: 200 }}
                        ref={(e: HTMLSelectElement) => this.freightElement = e || this.freightElement} >
                        <option value="">默认运费模板</option>
                    </select>
                </div>
            }
            ref={e => this.designer = e || this.designer} />
    }
}
